package com.luoxue.security;

import com.luoxue.entity.User;
import com.luoxue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtTokenFilter extends OncePerRequestFilter {

    @Resource
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (null != token) {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            String username = jwtTokenUtil.getUsernameFromToken(token);
            if (username != null) {
                User user = (User) jwtTokenUtil.getUser(username);
                if (user == null) {
                    user = this.userService.loadUserByUsername(username);
                    jwtTokenUtil.addUser(user);
                }
                if (user != null && jwtTokenUtil.validateToken(token, user)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, user, user.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }

}
